#coding: UTF-8
import os
import tornado.ioloop 
import tornado.web 
import tornado.websocket

from tornado.options import define , options


'''
db :mongodb
b/s:websocket	
'''
define("port" , default = 9988 , help = "Websocket run in given port!" , type = int)
#=======================================DEMOS====================================

#普通
class oneHandler(tornado.web.RequestHandler):
	def get(self):
		self.write("dwb is cools")

#携带地址的参数 访问http://localhost:9988/story/1
class twoHandler(tornado.web.RequestHandler):
	def get(self , storyid):
		self.write("the storyid is " + storyid)



#返回一个html页面 , post处理
class threeHandler(tornado.web.RequestHandler):
	#action 标明动作的目录
	def get(self):
		self.write('<html><body><form action="/three" method="post">'
                   '<input type="text" name="message">'
                   '<input type="submit" value="Submit">'
                   '</form></body></html>')
	def post(self):
		self.set_header("Content-Type", "text/plain")

		talk=self.get_argument('aa')  
		self.write("the client post msg is " + talk)

#返回一个错误,初始化传入参数
class fourHandler(tornado.web.RequestHandler):
	def initialize(self , errorstr):
		self.errorstr = errorstr
		print ("four handler the arg is " , errorstr)

	def get(self):
		self.write("the error string is " + str(self.errorstr))
		raise tornado.web.HTTPError(403)

#返回一个静态文件 注册为static目录 其他目录不行 原因未知。以后更换成重定向


#############################################SERVER###################################################

class Server(tornado.web.Application):
	def __init__(self):

		setting = dict(
			static_path = os.path.join(os.path.dirname(__file__) , "static"),
			cookie_secret = "todo"
			)

		handlers = [
			(r"/" , oneHandler),
			(r"/story/([0-9]+)" , twoHandler),
			(r"/three" , threeHandler),
			(r"/error" , fourHandler, dict(errorstr="123")),
			(r"/"  ,tornado.web.StaticFileHandler, dict(path=setting["static_path"]))
		]

		tornado.web.Application.__init__(self , handlers ,**setting)


def run():
	tornado.options.parse_command_line()
	app = Server()
	app.listen(options.port)
	print ("start run")
	tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
	run()